package com.getpebble.android.framework.protocol.outbound;

import com.getpebble.android.framework.protocol.EndpointId;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public abstract class PblOutboundMessage {
    protected byte[] mCachedGetBytes = null;
    final short mEndpointId;
    final List<Byte> mMessageBody = new ArrayList();

    public PblOutboundMessage(EndpointId endpointId) {
        this.mEndpointId = endpointId.getCode();
    }

    public synchronized void addBytes(Byte... bytes) {
        if (bytes != null) {
            this.mCachedGetBytes = null;
            for (Byte b : bytes) {
                this.mMessageBody.add(b);
            }
        }
    }

    public synchronized void addBytes(byte[] bytes) {
        if (bytes != null) {
            this.mCachedGetBytes = null;
            for (byte valueOf : bytes) {
                this.mMessageBody.add(Byte.valueOf(valueOf));
            }
        }
    }

    public synchronized void addBytes(ByteBuffer buffer) {
        this.mCachedGetBytes = null;
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        addBytes(bytes);
    }

    protected boolean areBytesCached() {
        return this.mCachedGetBytes != null;
    }

    public synchronized byte[] getBytes() {
        byte[] bArr;
        if (areBytesCached()) {
            bArr = this.mCachedGetBytes;
        } else {
            ByteBuffer bb = ByteBuffer.allocate(this.mMessageBody.size() + 4);
            bb.putShort((short) this.mMessageBody.size());
            bb.putShort(this.mEndpointId);
            for (Byte b : this.mMessageBody) {
                bb.put(b.byteValue());
            }
            this.mCachedGetBytes = bb.array();
            bArr = this.mCachedGetBytes;
        }
        return bArr;
    }
}
